<template>
  <div class="feedback-page">
    <a-page-header title="反馈管理" sub-title="处理用户反馈和建议">
      <template #extra>
        <a-space>
          <a-button 
            type="primary"
            :disabled="!selectedRowKeys.length"
            @click="handleBatchProcess"
          >
            <template #icon><check-outlined /></template>
            批量处理
          </a-button>
          <a-button @click="handleExport">
            <template #icon><export-outlined /></template>
            导出数据
          </a-button>
        </a-space>
      </template>
    </a-page-header>

    <!-- 统计卡片 -->
    <a-row :gutter="16" class="stats-row">
      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic 
            title="总反馈数" 
            :value="stats.total"
            :value-style="{ color: '#3f8600' }"
          >
            <template #prefix><message-outlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic 
            title="待处理" 
            :value="stats.pending"
            :value-style="{ color: '#faad14' }"
          >
            <template #prefix><clock-circle-outlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic 
            title="已处理" 
            :value="stats.resolved"
            :value-style="{ color: '#1890ff' }"
          >
            <template #prefix><check-circle-outlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
      <a-col :span="6">
        <a-card class="stat-card">
          <a-statistic 
            title="今日新增" 
            :value="stats.todayNew"
            :value-style="{ color: '#722ed1' }"
          >
            <template #prefix><plus-outlined /></template>
          </a-statistic>
        </a-card>
      </a-col>
    </a-row>

    <!-- 搜索筛选 -->
    <a-card class="search-card card-shadow">
      <a-form layout="inline">
        <a-form-item label="反馈类型">
          <a-select 
            v-model:value="searchForm.type" 
            placeholder="请选择" 
            style="width: 150px"
            allowClear
          >
            <a-select-option value="BUG">Bug反馈</a-select-option>
            <a-select-option value="FEATURE">功能建议</a-select-option>
            <a-select-option value="COMPLAINT">投诉举报</a-select-option>
            <a-select-option value="OTHER">其他</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="优先级">
          <a-select 
            v-model:value="searchForm.priority" 
            placeholder="请选择" 
            style="width: 120px"
            allowClear
          >
            <a-select-option value="LOW">低</a-select-option>
            <a-select-option value="NORMAL">普通</a-select-option>
            <a-select-option value="HIGH">高</a-select-option>
            <a-select-option value="URGENT">紧急</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="状态">
          <a-select 
            v-model:value="searchForm.status" 
            placeholder="请选择" 
            style="width: 120px"
            allowClear
          >
            <a-select-option value="PENDING">待处理</a-select-option>
            <a-select-option value="PROCESSING">处理中</a-select-option>
            <a-select-option value="RESOLVED">已处理</a-select-option>
            <a-select-option value="CLOSED">已关闭</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="关键词">
          <a-input 
            v-model:value="searchForm.keyword" 
            placeholder="标题/内容/用户"
            style="width: 200px"
            allowClear
          />
        </a-form-item>
        
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <template #icon><search-outlined /></template>
              搜索
            </a-button>
            <a-button @click="handleReset">
              <template #icon><reload-outlined /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
    
    <!-- 数据表格 -->
    <a-card class="table-card card-shadow">
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :loading="loading"
        :pagination="pagination"
        :row-selection="rowSelection"
        @change="handleTableChange"
        :expandable="{ expandedRowRender }"
        :scroll="{ x: 1200 }"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'type'">
            <a-tag :color="getTypeColor(record.type)">
              {{ getTypeText(record.type) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'priority'">
            <a-tag :color="getPriorityColor(record.priority)">
              {{ getPriorityText(record.priority) }}
            </a-tag>
          </template>
          
          <template v-else-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'hasImages'">
            <check-circle-filled v-if="record.images && record.images.length" style="color: #52c41a;" />
            <close-circle-outlined v-else style="color: #ccc;" />
          </template>
          
          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" size="small" @click="handleView(record)">
                查看
              </a-button>
              <a-button 
                type="link" 
                size="small" 
                @click="handleReply(record)"
                v-if="record.status !== 'RESOLVED' && record.status !== 'CLOSED'"
              >
                回复
              </a-button>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 回复弹窗 -->
    <a-modal
      v-model:open="replyModalVisible"
      title="回复反馈"
      width="600px"
      @ok="handleReplySubmit"
    >
      <a-form :label-col="{ span: 4 }">
        <a-form-item label="用户反馈">
          <a-card size="small" style="background: #fafafa;">
            <p style="margin: 0;">{{ currentRecord?.content }}</p>
          </a-card>
        </a-form-item>
        <a-form-item label="回复内容" required>
          <a-textarea
            v-model:value="replyContent"
            placeholder="请输入回复内容"
            :rows="6"
            :maxlength="500"
            show-count
          />
        </a-form-item>
        <a-form-item label="处理状态">
          <a-select v-model:value="replyStatus" style="width: 150px">
            <a-select-option value="PROCESSING">处理中</a-select-option>
            <a-select-option value="RESOLVED">已处理</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 查看详情弹窗 -->
    <a-modal
      v-model:open="viewModalVisible"
      title="反馈详情"
      width="700px"
      :footer="null"
    >
      <a-descriptions bordered :column="2">
        <a-descriptions-item label="反馈ID">
          {{ viewData.id }}
        </a-descriptions-item>
        <a-descriptions-item label="反馈类型">
          <a-tag :color="getTypeColor(viewData.type)">
            {{ getTypeText(viewData.type) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="用户">
          {{ viewData.username }}
        </a-descriptions-item>
        <a-descriptions-item label="联系方式">
          {{ viewData.contact || '未提供' }}
        </a-descriptions-item>
        <a-descriptions-item label="优先级">
          <a-tag :color="getPriorityColor(viewData.priority)">
            {{ getPriorityText(viewData.priority) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="状态">
          <a-tag :color="getStatusColor(viewData.status)">
            {{ getStatusText(viewData.status) }}
          </a-tag>
        </a-descriptions-item>
        <a-descriptions-item label="标题" :span="2">
          {{ viewData.title }}
        </a-descriptions-item>
        <a-descriptions-item label="详细内容" :span="2">
          {{ viewData.content }}
        </a-descriptions-item>
        <a-descriptions-item label="截图附件" :span="2" v-if="viewData.images && viewData.images.length">
          <a-image-preview-group>
            <a-image 
              v-for="(img, index) in viewData.images" 
              :key="index"
              :width="100"
              :src="img"
              style="margin-right: 8px;"
            />
          </a-image-preview-group>
        </a-descriptions-item>
        <a-descriptions-item label="提交时间">
          {{ viewData.createdAt }}
        </a-descriptions-item>
        <a-descriptions-item label="处理时间">
          {{ viewData.processedAt || '未处理' }}
        </a-descriptions-item>
        <a-descriptions-item label="管理员回复" :span="2" v-if="viewData.reply">
          <a-card size="small" style="background: #f0f9ff;">
            {{ viewData.reply }}
          </a-card>
        </a-descriptions-item>
      </a-descriptions>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, h, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import {
  CheckOutlined,
  ExportOutlined,
  MessageOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
  DownOutlined,
  CheckCircleFilled,
  CloseCircleOutlined
} from '@ant-design/icons-vue'
import {
  getFeedbackList,
  replyFeedback,
  updateFeedbackStatus
} from '@/api/feedback'

// 统计数据
const stats = reactive({
  total: 0,
  pending: 0,
  resolved: 0,
  todayNew: 0
})

// 搜索表单
const searchForm = reactive({
  type: undefined,
  priority: undefined,
  status: undefined,
  keyword: ''
})

// 表格配置
const loading = ref(false)
const dataSource = ref([])
const selectedRowKeys = ref([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showTotal: (total) => `共 ${total} 条`
})

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 60 },
  { title: '类型', key: 'type', width: 100 },
  { title: '标题', dataIndex: 'title', key: 'title', width: 180 },
  { title: '用户', dataIndex: 'username', key: 'username', width: 100 },
  { title: '优先级', key: 'priority', width: 90 },
  { title: '状态', key: 'status', width: 90 },
  { title: '附图', key: 'hasImages', width: 60 },
  { title: '提交时间', dataIndex: 'createdAt', key: 'createdAt', width: 160 },
  { title: '操作', key: 'action', width: 200, fixed: 'right' }
]

const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  }
}

// 弹窗配置
const replyModalVisible = ref(false)
const replyContent = ref('')
const replyStatus = ref('PROCESSING')
const currentRecord = ref(null)

const viewModalVisible = ref(false)
const viewData = reactive({})

// 初始化
onMounted(() => {
  loadData()
  loadStats()
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await getFeedbackList({
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    })
    if (res.code === 200) {
      dataSource.value = res.data.records || []
      pagination.total = res.data.total || 0
    }
  } catch (error) {
    message.error('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载统计
const loadStats = () => {
  // 这里可以调用统计接口
  stats.total = dataSource.value.length
  stats.pending = dataSource.value.filter(item => item.status === 'PENDING').length
  stats.resolved = dataSource.value.filter(item => item.status === 'RESOLVED').length
  stats.todayNew = 12
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  Object.assign(searchForm, {
    type: undefined,
    priority: undefined,
    status: undefined,
    keyword: ''
  })
  handleSearch()
}

// 表格变化
const handleTableChange = (pag) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadData()
}

// 展开行内容
const expandedRowRender = (record) => {
  return h('div', { style: { padding: '16px', backgroundColor: '#fafafa', borderRadius: '4px' } }, [
    h('p', { style: { margin: '0 0 8px 0', fontWeight: 'bold' } }, '反馈内容：'),
    h('p', { style: { margin: '0 0 12px 0' } }, record.content),
    record.reply ? h('div', [
      h('p', { style: { margin: '0 0 8px 0', fontWeight: 'bold', color: '#1890ff' } }, '管理员回复：'),
      h('p', { style: { margin: 0, padding: '8px 12px', background: '#e6f7ff', borderRadius: '4px' } }, record.reply)
    ]) : null
  ])
}

// 查看详情
const handleView = (record) => {
  Object.assign(viewData, record)
  viewModalVisible.value = true
}

// 回复
const handleReply = (record) => {
  currentRecord.value = record
  replyContent.value = ''
  replyStatus.value = 'PROCESSING'
  replyModalVisible.value = true
}

// 提交回复
const handleReplySubmit = async () => {
  if (!replyContent.value.trim()) {
    message.warning('请输入回复内容')
    return
  }
  
  try {
    const res = await replyFeedback(currentRecord.value.id, {
      reply: replyContent.value,
      status: replyStatus.value
    })
    if (res.code === 200) {
      message.success('回复成功')
      replyModalVisible.value = false
      loadData()
    }
  } catch (error) {
    message.error('回复失败')
  }
}

// 更新状态
const handleUpdateStatus = async (record, status) => {
  try {
    const res = await updateFeedbackStatus(record.id, status)
    if (res.code === 200) {
      message.success('状态更新成功')
      loadData()
    }
  } catch (error) {
    message.error('状态更新失败')
  }
}

// 批量处理
const handleBatchProcess = () => {
  message.info('批量处理功能开发中...')
}

// 导出
const handleExport = () => {
  message.info('导出功能开发中...')
}

// 辅助方法
const getTypeColor = (type) => {
  const colors = {
    BUG: 'red',
    FEATURE: 'blue',
    COMPLAINT: 'orange',
    OTHER: 'default'
  }
  return colors[type] || 'default'
}

const getTypeText = (type) => {
  const texts = {
    BUG: 'Bug反馈',
    FEATURE: '功能建议',
    COMPLAINT: '投诉举报',
    OTHER: '其他'
  }
  return texts[type] || type
}

const getPriorityColor = (priority) => {
  const colors = {
    LOW: 'default',
    NORMAL: 'blue',
    HIGH: 'orange',
    URGENT: 'red'
  }
  return colors[priority] || 'default'
}

const getPriorityText = (priority) => {
  const texts = {
    LOW: '低',
    NORMAL: '普通',
    HIGH: '高',
    URGENT: '紧急'
  }
  return texts[priority] || priority
}

const getStatusColor = (status) => {
  const colors = {
    PENDING: 'orange',
    PROCESSING: 'blue',
    RESOLVED: 'green',
    CLOSED: 'default'
  }
  return colors[status] || 'default'
}

const getStatusText = (status) => {
  const texts = {
    PENDING: '待处理',
    PROCESSING: '处理中',
    RESOLVED: '已处理',
    CLOSED: '已关闭'
  }
  return texts[status] || status
}
</script>

<style lang="scss" scoped>
.feedback-page {
  .stats-row {
    margin-bottom: 16px;

    .stat-card {
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    }
  }

  .search-card,
  .table-card {
    margin-bottom: 16px;
  }

  .card-shadow {
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  }
}
</style>

